import pygame
import random
import time
import math
import os  # 用于处理文件路径
# 初始化Pygame
pygame.init()
# 基础游戏参数
SCREEN_WIDTH = 720
SCREEN_HEIGHT = 768
FPS = 60
TIME_LIMIT = 20  # 游戏时间：20秒
KILL_TARGET = 80  # 打折券目标：击杀>80
# 敌人基础参数（难度递增基准）
BASE_ENEMY_SPEED_Y = 1.8  # 初始纵向速度（变快一倍）
BASE_ENEMY_SPEED_X = 1.2  # 初始横向速度（变快一倍）
BASE_ENEMY_BATCH_MIN = 2  # 初始每波最小数量
BASE_ENEMY_BATCH_MAX = 4  # 初始每波最大数量
# 敌人子弹基础参数
BASE_ENEMY_BULLET_SIZE = 30  # 基础大小（不变）
BASE_ENEMY_BULLET_SPEED = 1.728  # 初始速度
BASE_ENEMY_SHOOT_INTERVAL = 180  # 初始发射间隔（帧）
# 难度递增上限（基础值的1.5倍）
MAX_SPEED_MULTIPLIER = 1.5  # 速度上限
MAX_BATCH_MIN = int(BASE_ENEMY_BATCH_MIN * 1.5)  # 数量下限上限：3
MAX_BATCH_MAX = int(BASE_ENEMY_BATCH_MAX * 1.5)  # 数量上限上限：6
MAX_SHOOT_INTERVAL = int(BASE_ENEMY_SHOOT_INTERVAL / 1.5)  # 频率上限：120帧
# 自机与子弹参数
BULLET_SPEED = 15
TRACKING_BULLET_SPEED = BULLET_SPEED * 1.2
BULLET_SIZE = 15
BULLET_OFFSET = 50
PLAYER_HIT_POINT_RADIUS = 2
BASE_SPEED = 3
LOW_SPEED = BASE_SPEED * 1.5
HIGH_SPEED = BASE_SPEED * 3
ULT_DURATION = 5
ULT_RANGE = 720
ENEMY_RADIUS = 15
# 子弹频率阶梯
SHOOT_INTERVALS = {0:10, 5:8, 10:6, 15:4}
TRACKING_INTERVAL_RATIO = 2
# 颜色定义
WHITE = (255,255,255)
BLUE = (0,0,255)
YELLOW = (255,255,0)
PURPLE = (128,0,128)
RED = (255,0,0)
BLACK = (0,0,0)
GREEN = (0,255,0)
PINK = (255,105,180)
YELLOW_COUPON = (255,220,0)
RED_ALERT = (255,50,50)
ORANGE = (255,165,0)  # 难度提示色
# 自机类
class Player:
    def __init__(self):
        self.x = SCREEN_WIDTH // 2
        self.y = SCREEN_HEIGHT - 60
        self.shoot_timer = 0
        self.tracking_shoot_timer = 0
        self.direction = 1
        self.ult_used = False
        self.ult_active = False
        self.ult_remaining = 0
        self.flying_up = False
        self.fly_target_y = 50
    def move(self, dx, dy, current_speed):
        self.x = max(50, min(SCREEN_WIDTH-50, self.x + dx*current_speed))
        self.y = max(50, min(SCREEN_HEIGHT-50, self.y + dy*current_speed))
        if dx != 0:
            self.direction = dx // abs(dx)
    def fly_to_top(self):
        if self.y > self.fly_target_y:
            self.y -= 5
        else:
            self.flying_up = False
    def get_tip_position(self):
        return (self.x, self.y - 25)
    def draw(self, player_img):
        if player_img:
            img = pygame.transform.flip(player_img, True, False) if self.direction <0 else player_img
            if self.ult_active:
                alpha = 255 if int(pygame.time.get_ticks()/100)%2 ==0 else 180
                img.set_alpha(alpha)
            else:
                img.set_alpha(255)
            rect = img.get_rect(center=(self.x, self.y))
            screen.blit(img, rect)
        else:
            points = [(self.x, self.y - 25), (self.x - 20, self.y + 20), (self.x + 20, self.y + 20)]
            pygame.draw.polygon(screen, (255,0,0), points)
            pygame.draw.polygon(screen, BLACK, points, 2)
        pygame.draw.circle(screen, GREEN, (self.x, self.y), PLAYER_HIT_POINT_RADIUS, 0)
        if self.ult_active:
            pygame.draw.circle(screen, PINK, (self.x, self.y), ULT_RANGE//2, 2)
# 敌人类（随波数增强）
class Enemy:
    def __init__(self, enemy_id, speed_multiplier):
        self.id = enemy_id
        self.radius = ENEMY_RADIUS
        self.x = random.randint(100, SCREEN_WIDTH-100)
        self.y = random.randint(50, 100)
        self.speed_y = BASE_ENEMY_SPEED_Y * speed_multiplier  # 纵向速度随波数增强
        self.exploding = False
        self.explode_frame = 0
        self.shoot_timer = 0
        self.traj_type = random.choice([0,0,1,1,2])  # 轨迹类型权重
        self.speed_x = BASE_ENEMY_SPEED_X * speed_multiplier  # 横向速度随波数增强
        self.speed_multiplier = speed_multiplier  # 保存速度系数，用于传递给子弹
        if self.traj_type == 0:
            self.move_dir = random.choice(["left", "right"])  # 左右移动
        elif self.traj_type == 1:
            self.traj_timer = 0
            self.base_x = self.x  # 往返轨迹基准点
    def move(self):
        if self.exploding:
            return
        self.y += self.speed_y  # 纵向移动（加速）
        if self.traj_type == 0:  # 左右移动
            if self.move_dir == "left" and self.x > 50:
                self.x -= self.speed_x
            elif self.move_dir == "right" and self.x < SCREEN_WIDTH - 50:
                self.x += self.speed_x
            else:
                self.move_dir = "right" if self.move_dir == "left" else "left"  # 边界反转
        elif self.traj_type == 1:  # 往返轨迹
            self.traj_timer += 1
            amp = 20 * (self.speed_x / BASE_ENEMY_SPEED_X)  # 轨迹幅度随速度增强
            if self.traj_timer < 30:
                self.x = self.base_x - (self.traj_timer / 30) * amp
            else:
                self.x = self.base_x - ((60 - self.traj_timer) / 30) * amp
                if self.traj_timer >= 60:
                    self.traj_timer = 0
    def shoot(self, shoot_interval):
        self.shoot_timer += 1
        if self.shoot_timer >= shoot_interval and not self.exploding:
            self.shoot_timer = 0
            # 传递speed_multiplier给EnemyBullet（修复参数缺失错误）
            return EnemyBullet(self.x, self.y, self.id, self.speed_multiplier)
        return None
    def start_explode(self):
        self.exploding = True
        self.explode_frame = 0
    def draw(self):
        if self.exploding:
            colors = [WHITE, BLUE, WHITE]
            if self.explode_frame < len(colors)*3:
                color = colors[self.explode_frame//3]
                pygame.draw.circle(screen, color, (self.x, self.y), self.radius+5)
                self.explode_frame += 1
        else:
            pygame.draw.circle(screen, BLUE, (self.x, self.y), self.radius)
# 敌人子弹类（随波数增强）
class EnemyBullet:
    def __init__(self, x, y, enemy_id, speed_multiplier):
        self.x = x
        self.y = y
        self.speed = BASE_ENEMY_BULLET_SPEED * speed_multiplier  # 速度随波数增强
        self.size = BASE_ENEMY_BULLET_SIZE
        self.enemy_id = enemy_id
    def move(self):
        self.y += self.speed
    def draw(self):
        pygame.draw.rect(screen, RED, (self.x - self.size//2, self.y - self.size//2, self.size, self.size))
    def check_collision(self, player):
        bullet_rect = pygame.Rect(self.x - self.size//2, self.y - self.size//2, self.size, self.size)
        hit_point_rect = pygame.Rect(player.x - PLAYER_HIT_POINT_RADIUS, player.y - PLAYER_HIT_POINT_RADIUS, 
                                    PLAYER_HIT_POINT_RADIUS*2, PLAYER_HIT_POINT_RADIUS*2)
        return bullet_rect.colliderect(hit_point_rect)
# 自机直线子弹类
class StraightBullet:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = BULLET_SPEED
        self.size = BULLET_SIZE
    def move(self):
        self.y -= self.speed
    def draw(self):
        pygame.draw.rect(screen, YELLOW, (self.x - self.size//2, self.y, self.size, self.size*2))
    def check_collision(self, enemy):
        rect = pygame.Rect(self.x - self.size//2, self.y, self.size, self.size*2)
        enemy_rect = pygame.Rect(enemy.x - enemy.radius, enemy.y - enemy.radius, enemy.radius*2, enemy.radius*2)
        return rect.colliderect(enemy_rect)
# 自机追踪子弹类
class TrackingBullet:
    def __init__(self, x, y):
        self.x = x
        self.y = y
        self.speed = TRACKING_BULLET_SPEED
        self.size = BULLET_SIZE // 2
        self.target = None
    def set_target(self, enemies):
        if not enemies:
            self.target = None
            return
        min_dist = float('inf')
        closest_enemy = None
        for enemy in enemies:
            if not enemy.exploding:
                dist = math.hypot(self.x - enemy.x, self.y - enemy.y)
                if dist < min_dist:
                    min_dist = dist
                    closest_enemy = enemy
        self.target = closest_enemy
    def move(self):
        if self.target and not self.target.exploding:
            dx = self.target.x - self.x
            dy = self.target.y - self.y
            dist = max(1, math.hypot(dx, dy))
            dir_x = dx / dist
            dir_y = dy / dist
            self.x += dir_x * self.speed * 0.3
            self.y -= self.speed * 0.7 + dir_y * self.speed * 0.3
        else:
            self.y -= self.speed
    def draw(self):
        pygame.draw.rect(screen, PURPLE, (self.x - self.size//2, self.y, self.size, self.size*2))
    def check_collision(self, enemy):
        rect = pygame.Rect(self.x - self.size//2, self.y, self.size, self.size*2)
        enemy_rect = pygame.Rect(enemy.x - enemy.radius, enemy.y - enemy.radius, enemy.radius*2, enemy.radius*2)
        return rect.colliderect(enemy_rect)
# 生成敌机（随波数增加数量）
def spawn_enemies(current_wave, existing_enemies, next_enemy_id, speed_multiplier):
    # 每2波增加1个敌人数量（不超过上限）
    wave_increase = current_wave // 2
    current_min = min(BASE_ENEMY_BATCH_MIN + wave_increase, MAX_BATCH_MIN)
    current_max = min(BASE_ENEMY_BATCH_MAX + wave_increase, MAX_BATCH_MAX)
    batch_size = random.randint(current_min, current_max)
    
    new_enemies = []
    for _ in range(batch_size):
        valid = False
        while not valid:
            candidate = Enemy(next_enemy_id, speed_multiplier)
            next_enemy_id += 1
            too_close = False
            for enemy in existing_enemies + new_enemies:
                if not enemy.exploding and math.hypot(candidate.x - enemy.x, candidate.y - enemy.y) < 60:
                    too_close = True
                    break
            if not too_close:
                valid = True
                new_enemies.append(candidate)
    return new_enemies, next_enemy_id
# 获取自机子弹间隔
def get_shoot_interval(kill_count):
    for threshold in sorted(SHOOT_INTERVALS.keys(), reverse=True):
        if kill_count >= threshold:
            return SHOOT_INTERVALS[threshold]
    return SHOOT_INTERVALS[0]
# 游戏主循环
def game_loop():
    global screen
    screen = pygame.display.set_mode((SCREEN_WIDTH, SCREEN_HEIGHT))
    pygame.display.set_caption("Reimu's Bullet Hell Challenge (Full Version)")
    
    # 加载自机图片（用绝对路径确保正确加载）
    player_img = None
    img_error = ""
    # 加载背景图片（更换背景图）
    background_img = None
    background_img_error = ""
    # 获取代码所在目录的绝对路径
    script_dir = os.path.dirname(os.path.abspath(__file__))
    player_img_path = os.path.join(script_dir, "bread.png")  # 拼接自机图片路径
    background_img_path = os.path.join(script_dir, "6561761762323_.pic.jpg")  # Use new background image
    
    # 加载自机图片（用bread.png替换）
    player_img = None
    img_error = ""
    player_img_path = os.path.join(script_dir, "bread.png")
    try:
        player_img = pygame.image.load(player_img_path).convert_alpha()
        player_img = pygame.transform.scale(player_img, (50,50))
    except FileNotFoundError:
        img_error = f"bread.png not found! Please put it in: {script_dir}"
    except pygame.error:
        img_error = f"bread.png format error/corrupted (path: {player_img_path})"
    except Exception as e:
        img_error = f"Load failed: {str(e)}"
    if img_error:
        print(f"⚠️ Image Error: {img_error}")
    
    # 加载背景图片（更换背景图逻辑）
    try:
        # 加载背景图并缩放到屏幕尺寸（720×768）
        background_img = pygame.image.load(background_img_path).convert()
        background_img = pygame.transform.scale(background_img, (SCREEN_WIDTH, SCREEN_HEIGHT))
    except FileNotFoundError:
        background_img_error = f"Background image not found! Please put 6561761762323_.pic.jpg in: {script_dir}"
    except pygame.error:
        background_img_error = f"Background image format error/corrupted (path: {background_img_path})"
    except Exception as e:
        background_img_error = f"Background image load failed: {str(e)}"
    if background_img_error:
        print(f"⚠️ {background_img_error}")
    
    # 初始化游戏元素（原有逻辑）
    player = Player()
    straight_bullets = []
    tracking_bullets = []
    enemy_bullets = []
    enemies = []
    kill_count = 0
    discount_coupon = False
    start_time = time.time()
    last_spawn_time = start_time
    next_enemy_id = 0
    game_state = "running"
    enemy_health = {}
    
    # 难度递增计数器
    current_wave = 0  # 当前波数
    speed_multiplier = 1.0  # 速度倍增系数（初始1.0）
    clock = pygame.time.Clock()
    font = pygame.font.SysFont("SimHei", 36)
    small_font = pygame.font.SysFont("SimHei", 24)
    bold_font = pygame.font.SysFont("SimHei", 40, bold=True)
    while True:
        current_time = time.time()
        elapsed_time = current_time - start_time
        remaining_time = max(0, TIME_LIMIT - elapsed_time)
        shoot_interval = get_shoot_interval(kill_count)
        tracking_shoot_interval = shoot_interval * TRACKING_INTERVAL_RATIO
        # 事件处理（原有逻辑）
        for event in pygame.event.get():
            if event.type == pygame.QUIT:
                pygame.quit()
                return
            if event.type == pygame.KEYDOWN:
                if event.key == pygame.K_ESCAPE:
                    pygame.quit()
                    return
                if event.key == pygame.K_x and not player.ult_used and game_state == "running":
                    player.ult_active = True
                    player.ult_used = True
                    player.ult_remaining = ULT_DURATION
                    enemy_bullets.clear()
        if game_state == "running":
            # 速度控制（Shift减速）
            keys = pygame.key.get_pressed()
            shift_held = keys[pygame.K_LSHIFT] or keys[pygame.K_RSHIFT]
            current_speed = LOW_SPEED if shift_held else HIGH_SPEED
            # 移动控制
            dx = (keys[pygame.K_RIGHT] - keys[pygame.K_LEFT])
            dy = (keys[pygame.K_DOWN] - keys[pygame.K_UP])
            player.move(dx, dy, current_speed)
            # Z键发射双子弹
            if keys[pygame.K_z]:
                player.shoot_timer += 1
                if player.shoot_timer >= shoot_interval:
                    straight_bullets.append(StraightBullet(player.x - BULLET_OFFSET, player.y -25))
                    straight_bullets.append(StraightBullet(player.x + BULLET_OFFSET, player.y -25))
                    player.shoot_timer = 0
                player.tracking_shoot_timer += 1
                if player.tracking_shoot_timer >= tracking_shoot_interval:
                    tip_x, tip_y = player.get_tip_position()
                    tracking_bullets.append(TrackingBullet(tip_x, tip_y))
                    player.tracking_shoot_timer = 0
            # 生成新一波敌人（随波数增强）
            spawn_interval = random.uniform(1.5, 2.3)
            if current_time - last_spawn_time > spawn_interval:
                current_wave += 1
                speed_multiplier = min(speed_multiplier * 1.03, MAX_SPEED_MULTIPLIER)
                new_enemies, next_enemy_id = spawn_enemies(current_wave, enemies, next_enemy_id, speed_multiplier)
                enemies.extend(new_enemies)
                for enemy in new_enemies:
                    enemy_health[enemy.id] = 6
                last_spawn_time = current_time
            # 更新追踪子弹目标
            for bullet in tracking_bullets:
                bullet.set_target(enemies)
            # 子弹移动
            for bullet in straight_bullets[:]:
                bullet.move()
                if bullet.y < 0:
                    straight_bullets.remove(bullet)
            for bullet in tracking_bullets[:]:
                bullet.move()
                if bullet.y < 0:
                    tracking_bullets.remove(bullet)
            for bullet in enemy_bullets[:]:
                bullet.move()
                if bullet.y > SCREEN_HEIGHT:
                    enemy_bullets.remove(bullet)
            # 敌机移动
            for enemy in enemies[:]:
                enemy.move()
                if enemy.y > SCREEN_HEIGHT + enemy.radius:
                    enemies.remove(enemy)
                    if enemy.id in enemy_health:
                        del enemy_health[enemy.id]
            # 敌机发射子弹（频率随波数提高）
            current_shoot_interval = max(
                MAX_SHOOT_INTERVAL,
                int(BASE_ENEMY_SHOOT_INTERVAL / speed_multiplier)
            )
            for enemy in enemies:
                new_bullet = enemy.shoot(current_shoot_interval)
                if new_bullet:
                    enemy_bullets.append(new_bullet)
            # 碰撞检测
            # 直线子弹
            for bullet in straight_bullets[:]:
                for enemy in enemies[:]:
                    if not enemy.exploding and bullet.check_collision(enemy):
                        enemy_health[enemy.id] -= 3
                        straight_bullets.remove(bullet)
                        if enemy_health[enemy.id] <= 0:
                            kill_count += 1
                            enemy.start_explode()
                            enemy_bullets[:] = [b for b in enemy_bullets if b.enemy_id != enemy.id]
                            del enemy_health[enemy.id]
                        break
            # 追踪子弹
            for bullet in tracking_bullets[:]:
                for enemy in enemies[:]:
                    if not enemy.exploding and bullet.check_collision(enemy):
                        enemy_health[enemy.id] -= 1
                        tracking_bullets.remove(bullet)
                        if enemy_health[enemy.id] <= 0:
                            kill_count += 1
                            enemy.start_explode()
                            enemy_bullets[:] = [b for b in enemy_bullets if b.enemy_id != enemy.id]
                            del enemy_health[enemy.id]
                        break
            # 敌人子弹击中判定点
            for bullet in enemy_bullets[:]:
                if bullet.check_collision(player):
                    game_state = "fail"
                    for e in enemies:
                        if not e.exploding:
                            e.start_explode()
                    kill_count = 0
                    enemy_bullets.clear()
                    break
            # 敌机碰撞判定点
            for enemy in enemies:
                if not enemy.exploding and math.hypot(player.x - enemy.x, player.y - enemy.y) < (PLAYER_HIT_POINT_RADIUS + enemy.radius):
                    game_state = "fail"
                    for e in enemies:
                        if not e.exploding:
                            e.start_explode()
                    kill_count = 0
                    enemy_bullets.clear()
                    break
            # 大招逻辑
            if player.ult_active:
                player.ult_remaining -= 1/FPS
                for enemy in enemies[:]:
                    if not enemy.exploding and math.hypot(player.x - enemy.x, player.y - enemy.y) < ULT_RANGE:
                        kill_count += 1
                        enemy.start_explode()
                        enemy_bullets[:] = [b for b in enemy_bullets if b.enemy_id != enemy.id]
                        if enemy.id in enemy_health:
                            del enemy_health[enemy.id]
                enemy_bullets.clear()
                if player.ult_remaining <= 0:
                    player.ult_active = False
            # 时间到结束游戏
            if remaining_time <= 0:
                game_state = "success"
                player.flying_up = True
                discount_coupon = (kill_count > KILL_TARGET)
                for e in enemies:
                    if not e.exploding:
                        e.start_explode()
        # 成功后自机飞向顶部
        if game_state == "success" and player.flying_up:
            player.fly_to_top()
        # 绘制所有元素（关键修改：先画背景）
        # 1. 绘制背景图（新增：如果加载成功则显示背景，否则用白色填充）
        if background_img:
            screen.blit(background_img, (0, 0))  # 背景图从屏幕左上角(0,0)开始绘制
        else:
            screen.fill(WHITE)  # 背景加载失败时，用白色填充屏幕
        
        # 2. 图片错误提示（顶部，原有+新增背景错误提示）
        if img_error:
            error_text = small_font.render(f"[Image Error] {img_error}", True, RED_ALERT)
            screen.blit(error_text, (20, 5))
        if background_img_error:
            bg_error_text = small_font.render(f"[Background Error] {background_img_error}", True, RED_ALERT)
            screen.blit(bg_error_text, (20, 35))  # 背景错误提示在自机错误提示下方
        
        # 3. 难度信息（底部，美化输出）
        wave_text = small_font.render(
            f"Wave {current_wave} | Speed: {speed_multiplier:.2f}x | Enemy Shoot Interval: {current_shoot_interval} frames",
            True, ORANGE
        )
        screen.blit(wave_text, (20, SCREEN_HEIGHT - 30))
        
        # 4. 绘制游戏元素（自机、子弹、敌人等，原有逻辑）
        player.draw(player_img)  # 传递player_img参数
        for bullet in straight_bullets:
            bullet.draw()
        for bullet in tracking_bullets:
            bullet.draw()
        for bullet in enemy_bullets:
            bullet.draw()
        for enemy in enemies[:]:
            enemy.draw()
            if enemy.exploding and enemy.explode_frame >= 9:
                enemies.remove(enemy)
        
        # 5. UI信息绘制（美化输出）
        time_text = font.render(f"⏰ Time Left: {int(remaining_time)}s", True, BLACK)
        kill_text = bold_font.render(f"💥 Kills: {kill_count}/{KILL_TARGET} (> {KILL_TARGET} for coupon)", True, BLACK)
        speed_text = font.render(f"🚶 Speed: {'Low' if shift_held else 'High'}", True, BLACK)
        straight_rate = int(FPS / shoot_interval)
        tracking_rate = int(FPS / tracking_shoot_interval)
        bullet_text = font.render(f"🔫 Straight: {straight_rate}/s | Tracking: {tracking_rate}/s (Z to shoot)", True, BLACK)
        enemy_bullet_text = font.render(
            f"💣 Enemy Bullets: {int(FPS/current_shoot_interval):.1f}/s ({BASE_ENEMY_BULLET_SIZE}px)",
            True, BLACK
        )
        ult_info_text = font.render(f"🌟 Ultimate (X): {ULT_DURATION}s", True, BLACK)
        # 绘制UI（紧凑美观）
        y_offset = 40
        for info in [time_text, kill_text, speed_text, bullet_text, enemy_bullet_text, ult_info_text]:
            screen.blit(info, (20, y_offset))
            y_offset += info.get_height() + 10
        # 大招进度条美化
        if not player.ult_used:
            ult_text = font.render("🌟 Ultimate: Ready", True, BLACK)
        else:
            if player.ult_active:
                ult_width = int(200 * (player.ult_remaining / ULT_DURATION))
                pygame.draw.rect(screen, GREEN, (20, y_offset + 5, ult_width, 20))
                pygame.draw.rect(screen, BLACK, (20, y_offset + 5, 200, 20), 2)
                ult_text = font.render("🌟 Ultimate Active...", True, BLACK)
            else:
                ult_text = font.render("🌟 Ultimate: Used", True, BLACK)
        screen.blit(ult_text, (20, y_offset))
        y_offset += 40
        # 失败界面美化
        if game_state == "fail":
            fail_text = bold_font.render("❌ Game Over!", True, RED_ALERT)
            restart_text = font.render("Press ESC to exit or restart", True, BLACK)
            screen.blit(fail_text, (SCREEN_WIDTH//3, SCREEN_HEIGHT//2 - 30))
            screen.blit(restart_text, (SCREEN_WIDTH//3, SCREEN_HEIGHT//2 + 20))
        # 成功界面美化
        if game_state == "success" and not player.flying_up:
            success_text = bold_font.render("🎉 Challenge Complete!", True, GREEN)
            kill_result_text = font.render(f"Total Kills: {kill_count}", True, BLACK)
            screen.blit(success_text, (SCREEN_WIDTH//3, SCREEN_HEIGHT//2 - 100))
            screen.blit(kill_result_text, (SCREEN_WIDTH//3, SCREEN_HEIGHT//2 - 50))
            if discount_coupon:
                coupon_rect = (SCREEN_WIDTH//6, SCREEN_HEIGHT//2, 500, 100)
                pygame.draw.rect(screen, YELLOW_COUPON, coupon_rect)
                pygame.draw.rect(screen, BLACK, coupon_rect, 3)
                coupon_text1 = font.render("🎫 20% Game Merchandise Coupon", True, BLACK)
                coupon_text2 = font.render("Valid for 7 days | All categories", True, BLACK)
                screen.blit(coupon_text1, (coupon_rect[0]+30, coupon_rect[1]+30))
                screen.blit(coupon_text2, (coupon_rect[0]+30, coupon_rect[1]+70))
            else:
                tips_text = font.render(f"{KILL_TARGET - kill_count + 1} more kills for reward!", True, ORANGE)
                screen.blit(tips_text, (SCREEN_WIDTH//6, SCREEN_HEIGHT//2))
            restart_text = font.render("Press ESC to exit or restart", True, BLACK)
            screen.blit(restart_text, (SCREEN_WIDTH//3, SCREEN_HEIGHT//2 + 120))
        pygame.display.flip()
        clock.tick(FPS)
if __name__ == "__main__":
    game_loop()